package com.tanhua.sso.service;

import com.aliyun.oss.OSSClient;
import com.tanhua.sso.config.AliyunOSSConfig;
import com.tanhua.sso.vo.PicUploadResult;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;

/**
 * @Description AUTO
 * @ClassName PicUploadService
 * @Author ZhengXinjie
 * @date 2021.02.09 19:51
 */
@Service
public class PicUploadService {

    private final OSSClient ossClient;

    private final AliyunOSSConfig aliyunOSSConfig;


    @Autowired
    public PicUploadService(OSSClient ossClient, AliyunOSSConfig aliyunOSSConfig) {
        this.ossClient = ossClient;
        this.aliyunOSSConfig = aliyunOSSConfig;
    }

    // 定义允许上传的图片格式
    private final static String[] IMAGES_TYPE = new String[]{".bmp", ".jpg", ".jpeg", ".gif", ".png"};

    public PicUploadResult upload(MultipartFile uploadFile) {
        PicUploadResult picUploadResult = new PicUploadResult();

        // 文件后缀名是否合法
        boolean isLegal = false;

        for (String type : IMAGES_TYPE) {
            // 对上传文件的后缀名进行校验
            if (StringUtils.endsWithIgnoreCase(uploadFile.getOriginalFilename(), type)) {
                isLegal = true;
                break;
            }
        }

        if (!isLegal) {
            picUploadResult.setStatus("error");
            return picUploadResult;
        }

        // 设置上传文件路径
        String fileName = uploadFile.getOriginalFilename();
        String filePath = getFilePath(fileName);

        // 上传到阿里云
        try {
            ossClient.putObject(aliyunOSSConfig.getBucketName(), filePath, new ByteArrayInputStream(uploadFile.getBytes()));
        } catch (IOException e) {
            e.printStackTrace();
            // 上传失败
            picUploadResult.setStatus("error");
        }

        // 上传成功
        picUploadResult.setStatus("done");
        picUploadResult.setName(aliyunOSSConfig.getUrlPrefix() + filePath);
        picUploadResult.setUid(String.valueOf(System.currentTimeMillis()));

        return picUploadResult;

    }

    private String getFilePath(String sourceFileName) {
        DateTime dateTime = new DateTime();
        return "images/" +dateTime.toString("yyyy")
                + "/" + dateTime.toString("MM")
                + "/" + dateTime.toString("dd")
                + "/" + System.currentTimeMillis()
                + RandomUtils.nextInt(100, 9999) + "."
                + StringUtils.substringAfterLast(sourceFileName, ".");
    }
}

